package com.zzq.my.jetpacks.net.rxhttp

import android.content.Context
import android.net.ConnectivityManager
import android.text.TextUtils
import com.aisier.architecture.base.BaseApp
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import kotlinx.coroutines.TimeoutCancellationException
import rxhttp.RxHttpPlugins
import rxhttp.wrapper.exception.HttpStatusCodeException
import rxhttp.wrapper.exception.ParseException
import java.net.ConnectException
import java.net.HttpURLConnection
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException

/*
  * ================================================
  * 描述：Throwable  扩展字段
  * 作者：zhuangzeqin
  * 时间: 2022/1/26-14:01
  * 邮箱：zzq@eeepay.cn
  * 备注:
  * ----------------------------------------------------------------
  * You never know what you can do until you try !
  *      _              _           _     _   ____  _             _ _
  *     / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
  *    / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
  *   / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
  *  /_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
  *
  * 签名：最痛苦的事不是我失败了，而是我本可以.--zzq
  * ----------------------------------------------------------------
  * ================================================
  */
fun Throwable.show() {
    errorMsg.show()
}

fun String.show() {
    ToastUtils.showShort(this)
}

val Throwable.errorCode: Int
    get() =
        when (this) {
            is HttpStatusCodeException -> this.statusCode //Http状态码异常
            is ParseException -> this.errorCode.toIntOrNull() ?: -1     //业务code异常
            else -> -1
        }

val Throwable.errorMsg: String
    get() {
        return if (this is UnknownHostException) { //网络异常
            if (!isNetworkConnected(BaseApp.instance))
                "当前无网络，请检查你的网络设置"
            else
                "网络连接不可用，请稍后重试！"
        } else if (
            this is SocketTimeoutException  //okhttp全局设置超时
            || this is TimeoutException     //rxjava中的timeout方法超时
            || this is TimeoutCancellationException  //协程超时
        ) {
            "连接超时,请稍后再试"
        } else if (this is ConnectException) {
            "网络不给力，请稍候重试！"
        } else if (this is HttpStatusCodeException) {
            //请求失败异常
            if (TextUtils.isEmpty(message)) {
                val data = Gson().fromJson(result, BaseResponse::class.java)
                if (HttpURLConnection.HTTP_UNAUTHORIZED == data.code) {//401
                    // 标识码 401 被登录拦截了下来了
                    RxHttpPlugins.cancelAll()////取消所有的请求
//                    AppBus.getInstance().post(AppEvent(code, "401 token 失效")) //发布事件，在主界面进行订阅
                }
                "${data.message}"//那到请求结果返回的错误信息
            } else {
                "$message"
            }
        } else if (this is JsonSyntaxException) {  //请求成功，但Json语法异常,导致解析失败
            "数据解析失败,请检查数据是否正确"
        } else if (this is ParseException) {       // ParseException异常表明请求成功，但是数据不正确
            this.message ?: errorCode   //msg为空，显示code
        } else {
            message ?: this.toString()
        }
    }

/**
 * 判断网络是否连接
 */
private fun isNetworkConnected(context: Context): Boolean {
    val mConnectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val mNetworkInfo = mConnectivityManager.activeNetworkInfo
    if (mNetworkInfo != null) {
        return mNetworkInfo.isAvailable
    }
    return false
}
